import { useEffect, useState } from 'react'
import { useRequest } from 'ahooks'
import { useDispatch } from 'react-redux'
import { getUserInfoServices } from '../services/user'
import useGetUserInfo from './useGetUserInfo'
import { loginReducer } from '../store/userReducer'

function useLoadUserData() {
    const dispatch = useDispatch()
    const [waitingUserData, setWaitingUserData] = useState(true)
    const { username } = useGetUserInfo()

    // ajax获取用户信息
    const { run } = useRequest(getUserInfoServices, {
        manual: true,
        onSuccess(res) {
            const { username, nickname } = res
            // 存储到store中
            dispatch(loginReducer({ username, nickname }))
        },
        onFinally() {
            setWaitingUserData(false)
        },
    })

    useEffect(() => {
        // 如果已经有用户名，说明已经存储过登录细心
        if (username) {
            setWaitingUserData(false)
            return
        }
        // 如果redux store中没有用户信息，则加载
        run()
    }, [username])
    //   ajax加载完数据之后直接放到redux中，不用返回userInfo。所以只需要返回是否等待数据返回的状态即可
    return { waitingUserData }
}

export default useLoadUserData
